import { useState, useEffect } from 'react';
import api from '../api/axiosConfig';
import { Work } from '../types';
import WorkCard from '../components/WorkCard';

const WorksPage = () => {
  const [works, setWorks] = useState<Work[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchWorks = async () => {
      try {
        // 从我们功能完备的后端获取作品数据
        const { data } = await api.get('/works');
        setWorks(data);
      } catch (err) {
        setError('无法加载作品列表。');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchWorks();
  }, []); // 空依赖数组意味着这个 effect 只在组件挂载时运行一次

  if (loading) return <p>加载作品中...</p>;
  if (error) return <p style={{ color: 'red' }}>{error}</p>;

  return (
    <div style={{ padding: '0 2rem' }}>
      <h2>作品展示</h2>
      {works.length === 0 ? (
        <p>目前还没有已批准的作品。</p>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '1.5rem' }}>
          {works.map((work) => (
            <WorkCard key={work._id} work={work} />
          ))}
        </div>
      )}
    </div>
  );
};

export default WorksPage;